import { NextRequest, NextResponse } from 'next/server';
import { GloableResponseItem, ResponseEnum } from '@/utils/request/res';
import { Auth, type ExtendedNextApiRequest, LogOperation, ResponseHandler } from '@/utils/decorator';
import prisma from '@/utils/db/PrismaService';
import { BaseController } from '@/utils/request/BaseController';
import { GET as HttpGet, POST as HttpPost, PUT as HttpPut, DELETE as HttpDelete } from '@/utils/decorator';
import { createAllMethodHandlers } from '@/utils/request/routeRegistry';
import { Prisma } from '@prisma/client';

class SystemLogController extends BaseController {
    
    // 获取日志列表
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getLogList(request: ExtendedNextApiRequest) {
        const params: any = request.customBody;
        const page = parseInt(params.page || '1');
        const pageSize = parseInt(params.pageSize || '10');
        const offset = (page - 1) * pageSize;

        // 构建 SQL 查询条件
        let whereConditions = Prisma.sql`WHERE 1=1`;
        
        if (params.module) {
            whereConditions = Prisma.sql`${whereConditions} AND module LIKE ${`%${params.module}%`}`;
        }
        
        if (params.operationName) {
            whereConditions = Prisma.sql`${whereConditions} AND operation_name LIKE ${`%${params.operationName}%`}`;
        }
        
        if (params.userName) {
            whereConditions = Prisma.sql`${whereConditions} AND user_name LIKE ${`%${params.userName}%`}`;
        }
        
        if (params.status !== undefined && params.status !== '') {
            whereConditions = Prisma.sql`${whereConditions} AND status = ${parseInt(params.status)}`;
        }
        
        if (params.startTime && params.endTime) {
            whereConditions = Prisma.sql`${whereConditions} AND operation_time >= ${new Date(params.startTime)} AND operation_time <= ${new Date(params.endTime)}`;
        }

        try {
            // 查询日志列表 - 使用原生 SQL 查询
            const data = await prisma.$queryRaw<any[]>(Prisma.sql`
                SELECT *
                FROM sys_log
                ${whereConditions}
                ORDER BY operation_time DESC
                LIMIT ${pageSize} OFFSET ${offset}
            `);

            // 查询总数
            const total = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
                SELECT COUNT(*) as count
                FROM sys_log
                ${whereConditions}
            `);

            const formatData = data.map(item => ({
                ...item,
                key: item.id
            }));

            return GloableResponseItem(ResponseEnum.success, "", {
                data: formatData || [],
                total: total[0]?.count ? Number(total[0].count) : 0,
                page,
                pageSize,
            });
        } catch (error) {
            console.error('查询日志失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "查询失败", null);
        }
    }

    // 清空日志
    @Auth()
    @ResponseHandler() 
    @HttpDelete()
    @LogOperation({
        module: "日志管理",
        operationName: "清空日志"
    })
    static async clearLogs(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        
        try {
            if (data.days && data.days > 0) {
                // 删除指定天数之前的日志
                const cutoffDate = new Date();
                cutoffDate.setDate(cutoffDate.getDate() - data.days);
                
                await prisma.$queryRaw(Prisma.sql`
                    DELETE FROM sys_log 
                    WHERE operation_time < ${cutoffDate}
                `);
            } else {
                // 清空所有日志
                await prisma.$queryRaw(Prisma.sql`DELETE FROM sys_log`);
            }

            return GloableResponseItem(ResponseEnum.success, "清空成功", null);
        } catch (error) {
            console.error('清空日志失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "清空失败", null);
        }
    }

    // 获取日志详情
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getLogDetail(request: ExtendedNextApiRequest) {
        const params: any = request.customBody;
        const { id } = params;

        if (!id) {
            return GloableResponseItem(ResponseEnum.fail, "参数错误", null);
        }

        try {
            const log = await prisma.$queryRaw<any[]>(Prisma.sql`
                SELECT * FROM sys_log WHERE id = ${parseInt(id)}
            `);

            if (!log || log.length === 0) {
                return GloableResponseItem(ResponseEnum.fail, "日志不存在", null);
            }

            return GloableResponseItem(ResponseEnum.success, "", log[0]);
        } catch (error) {
            console.error('查询日志详情失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "查询失败", null);
        }
    }

    // 获取日志统计
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getLogStats(request: ExtendedNextApiRequest) {
        try {
            // 获取今日日志统计
            const today = new Date();
            const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
            const todayEnd = new Date(todayStart);
            todayEnd.setDate(todayEnd.getDate() + 1);

            const todayCount = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
                SELECT COUNT(*) as count
                FROM sys_log
                WHERE operation_time >= ${todayStart} 
                AND operation_time < ${todayEnd}
            `);

            const todayErrorCount = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
                SELECT COUNT(*) as count
                FROM sys_log
                WHERE operation_time >= ${todayStart} 
                AND operation_time < ${todayEnd}
                AND status = 1
            `);

            // 获取总日志数
            const totalCount = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
                SELECT COUNT(*) as count FROM sys_log
            `);

            // 获取模块操作统计（前10）
            const moduleStats = await prisma.$queryRaw<any[]>(Prisma.sql`
                SELECT module, COUNT(*) as count
                FROM sys_log
                GROUP BY module
                ORDER BY count DESC
                LIMIT 10
            `);

            return GloableResponseItem(ResponseEnum.success, "", {
                todayCount: Number(todayCount[0]?.count || 0),
                todayErrorCount: Number(todayErrorCount[0]?.count || 0),
                totalCount: Number(totalCount[0]?.count || 0),
                moduleStats: moduleStats.map(item => ({
                    module: item.module,
                    count: Number(item.count)
                }))
            });
        } catch (error) {
            console.error('查询日志统计失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "查询失败", null);
        }
    }
}

// 使用自动路由处理器创建所有HTTP方法处理函数
const handlers = createAllMethodHandlers(SystemLogController);

export const { GET, POST, PUT, DELETE } = handlers;